package com.sf.webside.service;

import com.sf.webside.bean.CmsRquestBean;
import com.sf.webside.config.Global;
import com.sf.webside.dao.CmsActicleDao;
import com.sf.webside.dao.CmsArticleDataDao;
import com.sf.webside.dao.CmsCategoryDao;
import com.sf.webside.entity.CmsArticleDataEntity;
import com.sf.webside.entity.CmsArticleEntity;
import com.sf.webside.entity.CmsCategoryEntity;
import com.sf.webside.vo.CmArticleVO;
import entity.PageVO;
import entity.ResultVO;
import entity.StatusCode;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import util.*;

import javax.annotation.Resource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by tanjing on 2019/2/21.
 */
@Service
public class CmsArticleService {
    private Logger logger= LoggerFactory.getLogger(CmsArticleService.class);
    @Resource
    private Global global;
    @Autowired
    private CmsActicleDao cmsActicleDao;
    @Autowired
    private CmsArticleDataDao cmsArticleDataDao;
    @Resource
    private IdWorker idWorker;
    @Autowired
    private CmsCategoryDao cmsCategoryDao;

    /**
     * 获取文章列表
     */
    public ResultVO list(String categoryId,String languageType,int page,int size){
        logger.info("list start {},{},{},{}",categoryId,languageType,page,size);
        Pageable pageable= PageRequest.of(page,size);
        Page<CmsArticleEntity> cmsArticleEntitiePage;
        if(categoryId.equals("-1")&&languageType.equals("-1")){//查询全部
            //查询全部文章
            cmsArticleEntitiePage = cmsActicleDao.findByDelFlagOrderByIssueDateDesc("0",pageable);
        }else if(categoryId.equals("-1")){
            //查询所有栏目文章
            cmsArticleEntitiePage = cmsActicleDao.findByLanguageTypeAndDelFlagOrderByIssueDateDesc(languageType,"0",pageable);
        }else if(languageType.equals("-1")){
            //查询所有语言文章
            cmsArticleEntitiePage = cmsActicleDao.findByCategoryIdAndDelFlagOrderByIssueDateDesc(categoryId,"0",pageable);
        }else{
            //查询按栏目+语言文章
            cmsArticleEntitiePage = cmsActicleDao.findByCategoryIdAndLanguageTypeAndDelFlagOrderByIssueDateDesc(categoryId,languageType,"0",pageable);
        }
        List<CmsArticleEntity> cmsArticleEntitieList=cmsArticleEntitiePage.getContent();
        List<CmArticleVO> cmArticleVOS=new ArrayList<>();
        for (CmsArticleEntity cmsArticleEntity:cmsArticleEntitieList) {
            CmArticleVO cmArticleVO = new CmArticleVO();
            BeanUtils.copyProperties(cmsArticleEntity,cmArticleVO);
            cmArticleVO.setCoverImage(global.replaceImagePreFix(cmArticleVO.getCoverImage()));
            cmArticleVO.setIssueDate(cmsArticleEntity.getIssueDate().getTime());
            CmsCategoryEntity cmsCategoryEntity=cmsCategoryDao.findByIdAndDelFlag(cmsArticleEntity.getCategoryId(),"0");
            String module=cmsCategoryEntity.getModule();
            if(module.equals("4")){
                CmsArticleDataEntity cmsArticleDataEntity=cmsArticleDataDao.findByIdAndDelFlag(cmsArticleEntity.getId(),"0");
                try {
                    String content=cmsArticleDataEntity.getContent();
                    if(StringUtils.isNoneBlank(content)){
                        String contentBase64=new String(Base64Utils.decodeFromString(content),"utf-8");
                        logger.info("list contentBase64 "+contentBase64);
                        cmArticleVO.setContent(global.replaceImagePreFix(contentBase64));
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    logger.info("list contentBase64 error");
                }
            }
            cmArticleVOS.add(cmArticleVO);
        }
        PageVO pageVO=new PageVO();
        pageVO.setDataList(cmArticleVOS);
        pageVO.setPageSize(size);
        pageVO.setCurrentPages(page+1);//默认从0开始，返回前端要+1;
        pageVO.setFirstPage(cmsArticleEntitiePage.isFirst());
        pageVO.setLastPage(cmsArticleEntitiePage.isLast());
        pageVO.setTotalElements(cmsArticleEntitiePage.getTotalElements());
        pageVO.setTotalPages(cmsArticleEntitiePage.getTotalPages());
        return ResultVOUtil.success(pageVO);
    }
    /**
     * 获取文章内容
     */
    public ResultVO getActicelCotent(String aritcleId){
        logger.info("getActicelCotent start {}",aritcleId);
        CmsArticleEntity cmsArticleEntity = cmsActicleDao.findByIdAndDelFlag(aritcleId,"0");
        CmsArticleDataEntity cmsArticleDataEntity = cmsArticleDataDao.findByIdAndDelFlag(aritcleId,"0");
        if(null==cmsArticleEntity){
            return ResultVOUtil.error(StatusCode.ERROR,"文章不存在");
        }
        String categoryId=cmsArticleEntity.getCategoryId();
        CmsCategoryEntity cmsCategoryEntity=cmsCategoryDao.findByIdAndDelFlag(categoryId,"0");
        if(null==cmsCategoryEntity){
            return ResultVOUtil.error(StatusCode.ERROR,"栏目不存在");
        }
        CmArticleVO cmArticleVO = new CmArticleVO();
        BeanUtils.copyProperties(cmsArticleEntity,cmArticleVO);
        cmArticleVO.setCoverImage(global.replaceImagePreFix(cmArticleVO.getCoverImage()));
        cmArticleVO.setIssueDate(cmsArticleEntity.getIssueDate().getTime());
        if(null!=cmsArticleDataEntity){
            try {
                String content=cmsArticleDataEntity.getContent();
                if(StringUtils.isNoneBlank(content)){
                    String contentBase64=new String(Base64Utils.decodeFromString(content),"utf-8");
                    logger.info("getActicelCotent contentBase64 "+contentBase64);
                    cmArticleVO.setContent(global.replaceImagePreFix(contentBase64));
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                logger.info("getActicelCotent contentBase64 error");
            }
        }
        return ResultVOUtil.success(cmArticleVO);
    }
    /**
     * 保存文章
     */
    public ResultVO save(CmsRquestBean cmsRquestBean){
        logger.info("save start {}",GsonUtils.getInstance().toJson(cmsRquestBean));
        String id=idWorker.nextId()+"";
        String categoryId=cmsRquestBean.getCategoryId();
        CmsCategoryEntity cmsCategoryEntity=cmsCategoryDao.findByIdAndDelFlag(categoryId,"0");
        if(null==cmsCategoryEntity){
            return ResultVOUtil.error(StatusCode.ERROR,"栏目不存在");
        }
        //保存文章
        CmsArticleEntity cmsArticleEntity=new CmsArticleEntity();
        BeanUtils.copyProperties(cmsRquestBean,cmsArticleEntity);
        cmsArticleEntity.setId(id);
        String converImageContent=replaceFileIp(cmsRquestBean.getCoverImage());
        cmsArticleEntity.setCoverImage(converImageContent);
        Date issueDate=(null==cmsRquestBean.getIssueDate()?new Date():new Date(cmsRquestBean.getIssueDate()));
        cmsArticleEntity.setIssueDate(issueDate);
        cmsArticleEntity.setCreateDate(new Date());
        cmsArticleEntity.setUpdateDate(new Date());
        cmsActicleDao.save(cmsArticleEntity);
        //保存文章详情
        CmsArticleDataEntity cmsArticleDataEntity=new CmsArticleDataEntity();
        cmsArticleDataEntity.setId(id);
        String content=replaceRichTestIp(cmsRquestBean.getContent());
        cmsArticleDataEntity.setContent(content);
        cmsArticleDataEntity.setCreateDate(new Date());
        cmsArticleDataEntity.setUpdateDate(new Date());
        cmsArticleDataDao.save(cmsArticleDataEntity);
        return ResultVOUtil.success();
    }
    /**
     * 修改文章
     */
    public ResultVO update(CmsRquestBean cmsRquestBean){
        logger.info("update start {}",GsonUtils.getInstance().toJson(cmsRquestBean));
        String id=cmsRquestBean.getId();
        CmsArticleEntity cmsArticleEntity = cmsActicleDao.findByIdAndDelFlag(id,"0");
        CmsArticleDataEntity cmsArticleDataEntity = cmsArticleDataDao.findByIdAndDelFlag(id,"0");
        if(null==cmsArticleEntity){
            return ResultVOUtil.error(StatusCode.ERROR,"文章不存在");
        }
        String categoryId= cmsRquestBean.getCategoryId();
        CmsCategoryEntity cmsCategoryEntity=cmsCategoryDao.findByIdAndDelFlag(categoryId,"0");
        if(null==cmsCategoryEntity){
            return ResultVOUtil.error(StatusCode.ERROR,"栏目不存在");
        }
        //保存文章
        BeanUtils.copyProperties(cmsRquestBean,cmsArticleEntity);
        Date issueDate=(null==cmsRquestBean.getIssueDate()?new Date():new Date(cmsRquestBean.getIssueDate()));
        cmsArticleEntity.setIssueDate(issueDate);
        cmsArticleEntity.setUpdateDate(new Date());
        String converImageContent=replaceFileIp(cmsRquestBean.getCoverImage());
        cmsArticleEntity.setCoverImage(converImageContent);
        cmsActicleDao.save(cmsArticleEntity);
        if(null!=cmsArticleDataEntity){
            //保存文章详情
            String content=replaceRichTestIp(cmsRquestBean.getContent());
            cmsArticleDataEntity.setContent(content);
            cmsArticleDataEntity.setUpdateDate(new Date());
            cmsArticleDataDao.save(cmsArticleDataEntity);
        }
        return ResultVOUtil.success();
    }
    /**
     * 删除文章
     */
    public ResultVO delete(String id){
        logger.info("update start {}",id);
        CmsArticleEntity cmsArticleEntity = cmsActicleDao.findByIdAndDelFlag(id,"0");
        CmsArticleDataEntity cmsArticleDataEntity = cmsArticleDataDao.findByIdAndDelFlag(id,"0");
        if(null==cmsArticleEntity){
            return ResultVOUtil.error(StatusCode.ERROR,"文章不存在");
        }
        cmsActicleDao.delete(cmsArticleEntity);
        if(null!=cmsArticleDataEntity){
            cmsArticleDataDao.delete(cmsArticleDataEntity);
        }
        return ResultVOUtil.success();
    }

    /**
     * 上传图片
     * @param multipartHttpServletRequest
     * @return
     */
    public ResultVO fileUpload(MultipartHttpServletRequest multipartHttpServletRequest){
        logger.info("fileUpload start ");
        String result;
        String fileUploadPath="/fileupload";
        String absolutePath=global.getImageAbsolutePath()+fileUploadPath;
        FileUtils.createDirectory(absolutePath.toString());
        Iterator<String> iter=multipartHttpServletRequest.getFileNames();
        StringBuffer stringBuffer=new StringBuffer();
        while (iter.hasNext()){
           MultipartFile multipartFile=multipartHttpServletRequest.getFile(iter.next().toString());
           if(null!=multipartFile&&!multipartFile.isEmpty()){
               String originalFilename=multipartFile.getOriginalFilename();
               String localFileName=absolutePath+"/"+originalFilename;
               try {
                   localFileName=FileUtils.isFileExists(localFileName); //判断文件是否存在
                   multipartFile.transferTo(new File(localFileName));
                   String newOriginalFilename=localFileName.substring(localFileName.lastIndexOf("/")+1);
                   String relativeFileName=new StringBuffer().append(global.getImageRelativePath()).append(fileUploadPath).append("/").append(newOriginalFilename).toString();
                   stringBuffer.append(relativeFileName).append(",");
               } catch (Exception e){
                   e.printStackTrace();
                   logger.info("上传图片失败");
                   return ResultVOUtil.error(StatusCode.ERROR,"上传图片失败");
               }
           }
        }
        String pathStr=stringBuffer.toString();
        logger.info("fileUpload end "+pathStr);
        if(StringUtils.isNoneBlank(pathStr)){
            result=pathStr.substring(0,pathStr.length()-1);
            return ResultVOUtil.success(StateToValueUtils.realImageAddProfix(result,global.getStaticFilePublicIp()));
        }
        return ResultVOUtil.error(StatusCode.ERROR,"暂无上传数据");
    }
    /**
     * 上传图片列表
     * @return
     */
    public ResultVO fileUploadList(){
        logger.info("fileUploadList start ");
        ArrayList resultList=new ArrayList();
        String fileUploadPath="/fileupload";
        String absolutePath=global.getImageAbsolutePath()+fileUploadPath;
        String relativePath=global.getImageRelativePath()+fileUploadPath;
        ArrayList<String> fileList= (ArrayList<String>) FileUtils.findChildrenList(new File(absolutePath+"/"),false);
        for (String str:fileList) {
            String filePath=global.getStaticFilePublicIp()+relativePath+"/"+str;
            resultList.add(filePath);
        }
        logger.info("fileUploadList end "+fileList.size());
        return ResultVOUtil.success(resultList);
    }
    /**
     * 上传图片删除
     * @return
     */
    public ResultVO fileUploadDelete(String fileName){
        logger.info("fileUploadDelete start fileName "+fileName);
        String fileUploadPath="/fileupload";
        String absolutePath=global.getImageAbsolutePath()+fileUploadPath;
        String filepath=absolutePath+"/"+fileName;
        boolean deleteFalg=FileUtils.deleteFile(filepath);
        logger.info("fileUploadDelete end deleteFalg "+deleteFalg);
        if(deleteFalg){
            return ResultVOUtil.success();
        }else{
            return ResultVOUtil.error(StatusCode.ERROR,"删除文件失败");
        }
    }
    /**
     * 替换文件前面的ip
     * @return
     */
    public String replaceFileIp(String file){
        if(StringUtils.isBlank(file)){
            return "";
        }
        //文章基本信息：封面图
        String content=file.replaceAll(global.getStaticFilePublicIp(),StatusCode.IP_PLACEHOLDER);
        return content;
    }
    /**
     * 替换富文本的ip
     * @return
     */
    public String replaceRichTestIp(String richTest){
        if(StringUtils.isBlank(richTest)){
            return "";
        }
        //文章基本信息：封面图
        String content=richTest.replaceAll(StatusCode.IP_PLACEHOLDER,global.getStaticFilePublicIp());
        String contentBase64=Base64Utils.encodeToString(content.getBytes());
        return contentBase64;
    }
}

